package com.pengheng.mqtt;

import com.pengheng.entity.MqttServer;
import com.pengheng.service.IMqttServerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 项目启动 监听主题
 */
@Slf4j
@Component
public class MqttClientListener implements ApplicationListener<ContextRefreshedEvent> {

    private final AtomicBoolean isInit = new AtomicBoolean(false);

    @Autowired
    private IMqttServerService mqttServerService;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        try {
            //防止重复触发
            if (!isInit.compareAndSet(false, true)) {
                return;
            }
            List<MqttServer> mqttServerEntityList = mqttServerService.list();
            for (MqttServer mqttServer : mqttServerEntityList) {
                MqttClientConnect mqttClientConnect = new MqttClientConnect();
                mqttClientConnect.setMqttClient(mqttServer, new MqttClientCallback(mqttServer.getClientId()));
                mqttClientConnect.sub(StringUtils.commaDelimitedListToStringArray(mqttServer.getClientTopic()));
                MqttClientConnect.mqttClients.put(mqttServer.getClientId(), mqttClientConnect);
                log.info("{}--连接成功！！订阅主题--{}", mqttServer.getClientId(), mqttServer.getClientTopic());
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

}